package com.yyk.yykywd.mvvm.ui

import android.os.Handler
import android.os.Message
import android.view.KeyEvent
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.GridLayoutManager
import com.google.gson.Gson
import com.yyk.yykywd.*
import com.yyk.yykywd.bean.BaseBean
import com.yyk.yykywd.config.HttpUrl
import com.yyk.yykywd.listenter.TakePhotoListenter
import com.yyk.yykywd.mvvm.adapter.AddMaterialAdapter
import com.yyk.yykywd.mvvm.base.BaseTakePhotoActivity
import com.yyk.yykywd.mvvm.entity.UploadBean
import com.yyk.yykywd.mvvm.view_model.AddPictureViewModel
import com.yyk.yykywd.util.DensityUtils
import com.yyk.yykywd.util.DialogUtil
import com.yyk.yykywd.util.TakePhotoHelper
import com.yyk.yykywd.util.ToastUtil
import com.yyk.yykywd.widght.SpaceItemDecoration
import kotlinx.android.synthetic.main.activity_add_material.*
import kotlinx.android.synthetic.main.rl_bottom.*
import org.devio.takephoto.model.TResult

class AddMaterialActivity : BaseTakePhotoActivity() {
    private lateinit var adapter: AddMaterialAdapter
    private lateinit var viewModel: AddPictureViewModel

    companion object {
        const val MAX_IMAGES = 6
    }

    private val handler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            val result = msg.obj as String
            val gson = Gson()
            val info: UploadBean = gson.fromJson(result, UploadBean::class.java)
            if (info.code != 1) {
                ToastUtil.showShort(mActivity, info.msg)
                return
            }

            viewModel.imgs.add(info.data)
            adapter.notifyDataSetChanged()
        }
    }

    override fun initView() {
        setTitle("添加素材")
        setBackArrow {
            backAndDelImg()
        }

        viewModel = ViewModelProviders.of(this).get(AddPictureViewModel::class.java)

        rv.layoutManager = GridLayoutManager(mActivity, 3)
        rv.addItemDecoration(SpaceItemDecoration(DensityUtils.dp2px(mActivity, 10f)))
        adapter = AddMaterialAdapter(mActivity, viewModel.imgs)
        adapter.maxImages = MAX_IMAGES
        rv.adapter = adapter
    }

    override fun setListener() {
        setAdapterChildClickListener(mActivity, adapter,
                getTakePhoto(),
                1, object : UploadClickListener {
            override fun clickIv() {

            }

            override fun clickRemove(position: Int) {
                viewModel.del_position = position
                viewModel.delSingleOrMulti = SINGLE
                viewModel.removeImg(viewModel.imgs[position])
            }

        })

        tv_execute.setOnClickListener {
            val text = getTextString(et_content)
            if (viewModel.imgs.size == 0 && text.isBlank()) {
                ToastUtil.showShort("图片和文字内容必须填写一项")
                return@setOnClickListener
            }
            viewModel.publishMaterial(text)
        }

        viewModel.responseMessage.observe(this, Observer<String> { t ->
            val msg = Message.obtain()
            msg.what = 1
            msg.obj = t
            handler.sendMessage(msg)
        })

        viewModel.delSuccess.observe(this, Observer<BaseBean> {
            if (viewModel.delSingleOrMulti == SINGLE) {
                viewModel.imgs.removeAt(viewModel.del_position)
                adapter.notifyDataSetChanged()
            } else {
                finish()
            }
        })

        viewModel.mPublishMaterial.observe(this,Observer<BaseBean>{
            ToastUtil.showShort(it.msg)
            if (it.code == 200) {
                finish()
            }
        })
    }

    override fun initData() {

    }

    override fun getLayoutId(): Int {
        return R.layout.activity_add_material
    }

    override fun takeSuccess(result: TResult) {
        viewModel.uploadContractImg(MATERIAL,result.image.compressPath)
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacksAndMessages(null)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            backAndDelImg()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun backAndDelImg() {
        val list = viewModel.imgs
        if (list.size > 0) {
            viewModel.delSingleOrMulti = MULTI
            viewModel.removeImg(listToString(list))
        } else {
            finish()
        }
    }
}
